<?php

namespace Beerus\Modules\SellGoods\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Category as mCategory;
use Doraemon\model\SellGoods\SellGoodsProductCategory as mSellGoodsProductCategory;
use Doraemon\model\SellGoods\SellGoodsProductCategoryRelation;
use Doraemon\service\SellGoods\ProductClassifyService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ClassifyMapController extends Controller
{
	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	/**
	 * 前台一级类目列表
	 * @param Content $content
	 * @return Content
	 */
	public function list(Content $content)
	{
		// 强制修改新建按钮的浮动样式
		Admin::style(".pull-left {float: right !important;margin-right: 10px} .sortable tr {cursor: default;}");

		$firstClassifies = ProductClassifyService::admClassifiesOrCategories();
		$gridModel = new pGridDataModel($firstClassifies['list']);
		$categoryGird = Admin::grid($gridModel, function (Grid $grid) {
			$grid->disableExport();
			$grid->disableCreateButton();
			$grid->tools(function ($tools) {
				$url = url('/admin/SellGoods/classifyMap/create');
				$button = '<div class="btn-group download">
				    <a class="btn-sm btn-success" href="'.$url.'"><i class="fa fa-plus"></i><span class="hidden-xs"> 新建一级分类</span></a>
				</div>';
				$tools->append($button);
			});
			$grid->disableFilter();
			$grid->disableRowSelector();
			$grid->disableColumnSelector();
			$grid->disablePagination();

			$grid->column('id')->width(70)->sort();
			$grid->column('name', '前台一级分类');
			$grid->column('data_status', '隐藏/显示')->switchToggle([
				'on' => [
					'value' => mSellGoodsProductCategory::STATUS_NORMAL,
					'text' => '展示'
				],
				'off' => [
					'value' => mSellGoodsProductCategory::STATUS_HIDE,
					'text' => '隐藏'
				]
			]);
			$grid->column('sub_classifies', '前台二级分类')->display(function () {
				$format = [];
				if ($this->sub_classifies) {
					$format = array_map(function ($classify) {
						return "<a href='/admin/SellGoods/classifyMap/{$classify['pid']}/edit/{$classify['id']}/edit'>{$classify['name']}</a>";
					}, $this->sub_classifies);
				}

				return $format;
			})->label('default');
			$grid->column('backend_classifies', '关联后台类目')->display(function () {
				$format = [];
				if ($this->backend_classifies) {
					foreach ($this->backend_classifies as $cate) {
						$format[] = "<a >{$cate}</a>";
					}
				}
				return $format;
			})->badge('gray');
		});

		return $content->header('前后台商品分类关联')->row($categoryGird);
	}

	/**
	 * 前台一级类目编辑页
	 * @param Content $content
	 * @param int $firClassifyId
	 * @return Content
	 */
	public function classifyEdit(Content $content, $firClassifyId = 0)
	{
		$tab = new Tab();

		// 基础信息
		$firClassifyInfo = [];
		if ($firClassifyId) {
			$firClassifyInfo = ProductClassifyService::admGetClassifyById($firClassifyId);
			$firClassifyInfo['backend_classify'] = SellGoodsProductCategoryRelation::getRelationCateIds($firClassifyId);;
		}

		$lastCategories = mCategory::getSelectLastStageCate(mSellGoodsProductCategory::DEEP_FIRST_CLASSIFY);

		$basicForm = new Form($firClassifyInfo);
		$basicForm->text('name', '一级分类名')->required();
		$basicForm->multipleSelect('backend_classify', '关联后台类目')->options($lastCategories);
		$basicForm->action('/admin/SellGoods/classifyMap/' . $firClassifyId . '/save');

		$tab->add('基础信息', $basicForm);

		if ($firClassifyId) {
			$secGird = $this->childClassifyGrid($firClassifyId, mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY, $firClassifyId);
			$tab->add('二级分类列表', $secGird);
		}

		$content->header('一级分类配置' . ($firClassifyId ? " - " . $firClassifyInfo['name'] : ""))
			->breadcrumb([
				'text' => '前台类目列表',
				'url' => '/SellGoods/classifyMap'
			], ['text' => '前台一级类目配置'])
			->row($tab);

		return $content;
	}

	/**
	 * 前台二/三级类目编辑页
	 * @param Request $request
	 * @param Content $content
	 * @param $firClassifyId
	 * @param int $secClassifyId
	 * @param int $thirdClassifyId
	 * @return Content
	 */
	public function childClassifyEdit(Request $request, Content $content, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
	{
		$deep = $request->route()->getName() ?:
			($thirdClassifyId ? mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY : mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY);
		$classifyId = $deep == mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY ? $secClassifyId : $thirdClassifyId;

		$tab = new Tab();
		$childClassifyInfo = [];
		if ($classifyId) {
			$childClassifyInfo = ProductClassifyService::admGetClassifyById($classifyId);
			$childClassifyInfo['backend_classify'] = SellGoodsProductCategoryRelation::getRelationCateIds($classifyId);
		}
		$lastCategories = mCategory::getSelectLastStageCate(mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY);

		$basicForm = new Form($childClassifyInfo);
		$basicForm->hidden('id');
		$basicForm->hidden('deep')->default($deep);
		$basicForm->hidden('pid')->default($deep == mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY ? $firClassifyId : $secClassifyId);
		$basicForm->text('name', mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep] . '级分类名')->required();;
		$basicForm->multipleSelect('backend_classify', '关联后台类目')->options($lastCategories);

		switch ($deep) {
			case mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY:
				$basicForm->action('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/save');
				$content->header('前台' . mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep] . '级类目配置' . ($classifyId ? " - " . $childClassifyInfo['name'] : ""))
					->breadcrumb([
						'text' => '前台类目列表',
						'url' => '/SellGoods/classifyMap'
					], [
						'text' => '前台一级类目列表',
						'url' => '/SellGoods/classifyMap/' . $firClassifyId . '/edit'
					], ['text' => '前台二级级类目配置']);
				break;
			case mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY:
				$basicForm->action('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/save');
				$content->header('前台' . mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep] . '级类目配置' . ($classifyId ? " - " . $childClassifyInfo['name'] : ""))
					->breadcrumb([
						'text' => '前台类目列表',
						'url' => '/SellGoods/classifyMap'
					], [
						'text' => '前台一级类目列表',
						'url' => '/SellGoods/classifyMap/' . $firClassifyId . '/edit'
					], [
						'text' => '前台二级类目列表',
						'url' => '/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit'
					], ['text' => '前台三级级类目配置']);
				break;
		}

		$tab->add('基础信息', $basicForm);
		if ($classifyId && $deep < mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY) {
			$secGird = $this->childClassifyGrid($classifyId, $deep + 1, $childClassifyInfo['pid']);
			$tab->add('三级分类列表', $secGird);
		}

		switch ($deep) {
			case mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY:
				$basicForm->action('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/save');
				break;
			case mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY:
				$basicForm->action('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/save');
				break;
		}
		$content->row($tab);

		return $content;
	}

	/**
	 * 保存一级类目修改
	 * @param Request $request
	 * @param int $firClassifyId
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function saveClassify(Request $request, $firClassifyId = 0)
	{
		$data = [
			'name' => $request->input('name'),
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username,
			'deep' => mSellGoodsProductCategory::DEEP_FIRST_CLASSIFY,
		];

		$backend_classify = $request->input(['backend_classify']);
		$backend_classify = array_filter($backend_classify);

		try {
			if ($firClassifyId) {
				ProductClassifyService::admEditClassify($data, $firClassifyId, $backend_classify);
			} else {
				$firClassifyId = ProductClassifyService::admAddClassifies($data, $backend_classify);
			}
		} catch (\Exception $e) {
			$error = new MessageBag([
				'title' => $e->getMessage()
			]);

			return back()->with(compact('error'));
		}

		$success = new MessageBag([
			'title' => '保存成功'
		]);

		return redirect('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit')->with(compact('success'));
	}

	/**
	 * 保存二/三级类目修改
	 * @param Request $request
	 * @param $firClassifyId
	 * @param int $secClassifyId
	 * @param int $thirdClassifyId
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function saveChildClassify(Request $request, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
	{
		$classifyId = $request->input('id');
		$deep = $request->input('deep');

		$data = [
			'name' => $request->input('name'),
			'pid' => $request->input('pid'),
			'deep' => $deep,
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username,
		];

		$backend_classify = array_filter($request->input('backend_classify'));

		try {
			if ($classifyId) {
				// 更新基础类目信息
				ProductClassifyService::admEditClassify($data, $classifyId, $backend_classify);
			} else {
				$classifyId = ProductClassifyService::admAddClassifies($data, $backend_classify);
			}

		} catch (\Exception $e) {
			$error = new MessageBag([
				'title' => $e->getMessage()
			]);
			return back()->with(compact('error'));
		}

		$success = new MessageBag([
			'title' => '保存成功'
		]);

		switch ($deep) {
			case mSellGoodsProductCategory::DEEP_SECOND_CLASSIFY:
				return redirect('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/edit')->with(compact('success'));
				break;
			case mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY:
				return redirect('/admin/SellGoods/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/edit')->with(compact('success'));
				break;
		}
	}

	/**
	 * 前台类目排序
	 * @param Request $request
	 */
	public function sort(Request $request)
	{
		$sortInfo = $request->input('sort');
		ProductClassifyService::admSortClassifies($sortInfo);
	}

	/**
	 * 前台子类目列表
	 * @param $childClassifyId
	 * @param $deep
	 * @param int $firstClassifyId
	 * @return string
	 */
	private function childClassifyGrid($childClassifyId, $deep, $firstClassifyId = 0)
	{
		Admin::style(".sortable tr {cursor: default;}");

		$childClassifies = ProductClassifyService::admClassifiesOrCategories($childClassifyId);
		$gridModel = new pGridDataModel($childClassifies['list']);

		return Admin::grid($gridModel, function (Grid $grid) use ($deep, $firstClassifyId, $childClassifyId) {
			$grid->disableExport();
			$grid->disableFilter();
			$grid->disableRowSelector();
			$grid->disableColumnSelector();
			$grid->disablePagination();

//			$grid->disableCreateButton();
//			$grid->tools(function ($tools) use ($deep, $childClassifyId) {
//				$url = url("/admin/SellGoods/classifyMap/{$childClassifyId}/edit/create");
//				$level = mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep];
//				$button = '<div class="btn-group download">
//				    <a class="btn-sm btn-success" href="'.$url.'"><i class="fa fa-plus"></i><span class="hidden-xs"> 新建'.$level.'级分类</span></a>
//				</div>';
//				$tools->append($button);
//			});

			$grid->column('id')->width(70)->sort();
			$grid->column('name', '前台' . mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep] . '级分类');
			$grid->column('data_status', '隐藏/显示')->switchToggle([
				'on' => [
					'value' => mSellGoodsProductCategory::STATUS_NORMAL,
					'text' => '展示'
				],
				'off' => [
					'value' => mSellGoodsProductCategory::STATUS_HIDE,
					'text' => '隐藏'
				]
			]);
			if ($deep < mSellGoodsProductCategory::DEEP_THIRD_CLASSIFY) {
				$grid->column('sub_classifies', '前台' . mSellGoodsProductCategory::DEEP_CLASSIFY_DISPLAY[$deep + 1] . '级分类')->display(function () use ($deep, $firstClassifyId) {
					$format = [];
					if ($this->sub_classifies) {
						foreach ($this->sub_classifies as $classify) {
							$format[] = "<a href='/admin/SellGoods/classifyMap/{$firstClassifyId}/edit/{$classify['pid']}/edit/{$classify['id']}/edit'>{$classify['name']}</a>";
						}
					}
					return $format;
				})->label('default');
			}
			$grid->column('backend_classifies', '关联后台类目')->display(function () {
				$format = [];
				if ($this->backend_classifies) {
					foreach ($this->backend_classifies as $cate) {
						$format[] = "<a>{$cate}</a>";
					}
				}
				return $format;
			})->badge('gray');
		})->render();
	}

	/**
	 * 删除前台类目
	 * @param $firClassifyId
	 * @param int $secClassifyId
	 * @param int $thirdClassifyId
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function delClassify($firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
	{
		$classifyId = $thirdClassifyId ?: ($secClassifyId ?: $firClassifyId);
		$admin = [
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username
		];
		ProductClassifyService::admDelClassify($classifyId, $admin);

		return response()->json([
			'status' => true,
			'message' => '删除成功'
		]);
	}

	/**
	 * 修改前台类目
	 * @param Request $request
	 * @param $firClassifyId
	 * @param int $secClassifyId
	 * @param int $thirdClassifyId
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function editClassify(Request $request, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
	{
		$classifyId = $thirdClassifyId ?: ($secClassifyId ?: $firClassifyId);
		$data = $request->all();
		ProductClassifyService::admHideClassify($data, $classifyId);

		return response()->json([
			'status' => true,
			'message' => '修改成功'
		]);
	}
}
